package com.xxx.springboot.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.xxx.springboot.pojo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * EasyCaptcha验证码
 */
@Controller
@RequestMapping(value = "/", produces = "application/json;charset=utf-8")
public class CaptchaController extends BaseController {

    /**
     * 获取图片验证码
     */
    @RequestMapping("/getCaptchaImg")
    public void getCaptchaImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // ① 使用自带的工具类：CaptchaUtil封装了输出验证码、存session、判断验证码等功能
        // 4位字母+数字
//        CaptchaUtil.out(request, response);
        // ② 设置位数5
//        CaptchaUtil.out(5, request, response);
        // ③ 设置宽150、高48、位数6
//        CaptchaUtil.out(150, 48, 6, request, response);
        // ④ 使用gif验证码
//        GifCaptcha gifCaptcha = new GifCaptcha(130, 48,4);
//        CaptchaUtil.out(gifCaptcha, request, response);
        // ⑤ 算术类型验证码
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
//        captcha.setLen(3);  // 几位数运算，默认是两位
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        String text = captcha.text();  // 获取运算的结果：5
        System.out.println(text);
        captcha.out(response.getOutputStream());  // 输出验证码
        // 如果不适用自带的工具类CaptchaUtil，则需要自己将验证码内容放入session
        request.getSession().setAttribute("captcha", text);
    }

    /**
     * 验证图片验证码是否正确
     */
    @RequestMapping("/chkCaptchaImg")
    @ResponseBody
    public String chkCaptchaImg(HttpServletRequest request, String verCode) {
        if (!CaptchaUtil.ver(verCode, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            return Result.fail("验证码不正确");
        }
        return Result.ok();
    }

}
